<template>
    <ContentWrap v-loading="formLoading">
        <el-form ref="formRef" :model="formData" label-width="140px" label-suffix="：" :rules="rules" class="w-60%">
            <el-form-item label="二维码名称" prop="codeName">
                <el-input v-model="formData.codeName" :maxlength="50" placeholder="请输入二维码名称" :disabled="isDetail" />
            </el-form-item>
            <el-form-item label="二维码图片" prop="codeUrl">
                <UploadImg v-model="formData.codeUrl" :disabled="isDetail" height="80px" />
            </el-form-item>
            <el-form-item label="简介" prop="codeDescription">
                <el-input type="textarea" :rows="4" v-model="formData.codeDescription" :maxlength="300" show-word-limit placeholder="请输入简介" :disabled="isDetail" />
            </el-form-item>
            <el-form-item label="详细地址" prop="addressDetail">
                <el-input v-model="formData.addressDetail" readonly placeholder="请点击选择门店地址" @click="handleSelectAddress" />
            </el-form-item>
            <el-form-item label="群管理员" prop="groupAdmin">
                <el-select v-model="formData.groupAdmin" placeholder="请选择群管理员" :disabled="isDetail">
                    <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.nickname" />
                </el-select>
            </el-form-item>
            <el-form-item label="联系电话" prop="groupPhone">
                <el-input v-model="formData.groupPhone" :maxlength="11" placeholder="请输入联系电话" :disabled="isDetail" />
            </el-form-item>
            <el-form-item label="">
                <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
                    保存
                </el-button>
                <el-button @click="close">返回</el-button>
            </el-form-item>
        </el-form>
        <el-dialog v-model="showAddressSelect" title="地址选择" width="60%" :close-on-click-modal="false">
            <iframe id="mapPage" width="100%" height="600px" frameborder=0
                src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=JXWBZ-2CX34-OPOU2-DECPC-PN47J-57BQI&referer=javascript_map">
            </iframe>
        </el-dialog>
    </ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as QrcodeApi from '@/api/system/qrcode'
import * as AreaApi from '@/api/system/area'
import * as UserApi from '@/api/system/user'
import { convertToInteger, floatToFixed2, formatToFraction } from '@/utils'
import request from '@/config/axios'

defineOptions({ name: 'QrcodeForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { params, name } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('info') // Tag 激活的窗口
const isDetail = ref(false) // 是否查看详情
const formRef = ref();
const showAddressSelect = ref(false) // 地址选择弹窗
// 表单数据
const formData = ref<QrcodeApi.Qrcode>({
    codeName: '', // 二维码名称
    codeUrl: '', // 图片地址
    codeDescription: '', // 简介
    addressDetail: '', // 服务小区地址
    latitude: '', // 纬度
    longitude: '', // 经度
    groupAdmin: '', // 群管理员
    groupPhone: '', // 群管理员联系方式
})
const rules = reactive({
    codeName: [required], // 二维码名称
    codeUrl: [required], // 图片地址
    codeDescription: [required], // 简介
    addressDetail: [required], // 服务小区地址
    latitude: [required], // 纬度
    longitude: [required], // 经度
    groupAdmin: [required], // 群管理员
    groupPhone: [{
        required,
        pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
        message: '请输入正确的手机号码',
        trigger: 'blur'
    }], // 群管理员联系方式
})

/** 查询管理员 */
const userList = ref([]);
const getUserList = async () => {
    try {
        const res = (await UserApi.getSimpleUserList()) as UserApi.UserVO
        userList.value = res.filter(item => item.id !== 1);
    } finally {
        
    }
}

/** 获得详情 */
const getDetail = async () => {
    if ('QrcodeDetail' === name) {
        isDetail.value = true
    }
    const id = params.id as unknown as number
    if (id) {
        formLoading.value = true
        try {
            const res = (await QrcodeApi.getQrcodeDetail(id)) as QrcodeApi.Qrcode
            formData.value = res
        } finally {
            formLoading.value = false
        }
    }
}


const getLocation = (event) => {
    // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
    var loc = event.data;
    // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
    if (loc && loc.module == 'locationPicker') {
        showAddressSelect.value = false;
        formData.value.addressDetail = loc.poiaddress;
        formData.value.latitude = loc.latlng.lat;
        formData.value.longitude = loc.latlng.lng;
    }
}

const handleSelectAddress = () => {
    showAddressSelect.value = true;
}

const changeTime = () => {
    formData.value.closingTime = '';
}

/** 提交按钮 */
const submitForm = async () => {
    // 提交请求
    formLoading.value = true
    try {

        // getLocation();
        // 校验各表单
        await unref(formRef)?.validate()

        const deepCopyFormData = cloneDeep(unref(formData.value)) as QrcodeApi.Qrcode

        // 校验都通过后提交表单
        const data = deepCopyFormData as QrcodeApi.Qrcode
        const id = params.id as unknown as number


        if (!id) {
            await QrcodeApi.createQrcode(data)
            message.success(t('common.createSuccess'))
        } else {
            await QrcodeApi.updateQrcode(data)
            message.success(t('common.updateSuccess'))
        }
        close()
    } finally {
        formLoading.value = false
    }
}

/** 关闭按钮 */
const close = () => {
    delView(unref(currentRoute))
    push({ name: 'SystemQrcode' })
}

/** 初始化 */
onMounted(async () => {
    getUserList();
    await getDetail()

    window.addEventListener('message', getLocation, false);
})

onUnmounted(() => {
    window.removeEventListener('message', getLocation, false);
})
</script>
